<script setup lang="ts">
import { addEmployeeAPI, delEmployeeAPI, editEmployeeAPI, getEmployeeListAPI, getRoleListAPI, resetPasswordAPI } from '@/apis/system';
import type { AddEmployeeParams, Employee, EmployeeListParams, Role } from '@/types/system';
import { ElMessage, ElMessageBox, type FormInstance } from 'element-plus';
import { ref } from 'vue';

const params = ref<EmployeeListParams>({
  page: 1,
  pageSize: 10,
  name: ''
})
const list = ref<Employee[]>([])

const total = ref(0)
const getList = async () => {
  const res = await getEmployeeListAPI(params.value)
  console.log('res',res)
  list.value = res.data.rows
  total.value = res.data.total
}
getList()
const onSearch = () => {
  params.value.page = 1
  getList()
}

// 添加员工部分
const addFormInit = () => {
  return {
    name: '',
    userName: '',
    phonenumber: '',
    roleId: undefined,
    status: 0,
  }
}
const addForm = ref<AddEmployeeParams>(addFormInit())
const addDialogVisible = ref(false)
const isLoading = ref(false)
const rules = {
  name: [{ required: true, message: '请输入员工姓名', trigger: 'blur' }],
  userName: [{ required: true, message: '请输入登录账号', trigger: 'blur' }],
  phonenumber: [
    { required: true, message: '请输入联系方式', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  roleId: [{ required: true, message: '请选择分配角色', trigger: 'change' }],
  status: [{ required: true, message: '请选择员工状态', trigger: 'change' }]
}
const addFormRef = ref<FormInstance>()
const roleList = ref<Role[]>([])
const getRoleList = async () => {
  // 这里需要调用获取角色列表的 API
  const res = await getRoleListAPI()
  roleList.value = res.data
}
getRoleList()
const onOpen = () => {
  addDialogVisible.value = true
}

const onClose = () => {
  addDialogVisible.value = false
  addForm.value = addFormInit()
  addFormRef.value?.resetFields()
  isLoading.value = false
}

const onSubmit = async() => {
  try {
    addFormRef.value?.validate()
    isLoading.value = true
    if(addForm.value.id){
      await editEmployeeAPI(addForm.value)
      ElMessage.success('编辑成功')
    }else{
      await addEmployeeAPI(addForm.value)
      ElMessage.success('添加成功')
    }
    onClose()
    getList()
  } catch (error) {
    isLoading.value = false
  }
}
// 删除员工
const handleDelete = async(id: number) => {
  ElMessageBox.confirm('确定删除该员工吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    await delEmployeeAPI(id)
    ElMessage.success('删除成功')
    getList()
  }).catch(() => {})
}
// 重置密码
const handleResetPassword = async(id: number) => {
  ElMessageBox.confirm('确定重置密码为123456吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    await resetPasswordAPI(id)
    ElMessage.success('重置密码成功')
  })
  .catch(() => {})
}
// 编辑员工
const onEdit = (row: Employee) => {
  console.log('row',row)
  addDialogVisible.value = true
  addForm.value = {
    name: row.name,
    userName: row.userName,
    phonenumber: row.phonenumber,
    roleId: row.roleId,
    status: row.status,
    id: row.id,
    roleName: row.roleName,
  }
}
</script>

<template>
  <div class="building-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <div class="search-label">员工姓名：</div>
      <el-input clearable placeholder="请输入员工姓名"  class="search-main" v-model="params.name" />
      <el-button type="primary" @click="onSearch">查询</el-button>
    </div>
    <div class="create-container">
      <el-button type="primary" @click="onOpen">添加员工</el-button>
    </div>
    <!-- 表格区域 -->
    <div class="table">
      <el-table style="width: 100%" :data="list">
        <el-table-column type="index" label="序号" />
        <el-table-column label="员工姓名" prop="name" />
        <el-table-column label="登陆账号" prop="userName" />
        <el-table-column label="联系方式" prop="phonenumber" />
        <el-table-column label="角色" prop="roleName" />
        <el-table-column label="状态" prop="status">
          <template #default="scope">
            <el-tag v-if="scope.row.status === 1" type="success">启用</el-tag>
            <el-tag v-else type="danger">禁用</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="添加时间" prop="createTime" width="180px" />
        <el-table-column label="操作" width="200px">
          <template #default="{row}">
            <el-button size="small" link type="primary" @click="onEdit(row)">编辑</el-button>
            <el-button size="small" link type="primary" @click="handleDelete(row.id)">删除</el-button>
            <el-button size="small" link type="primary" @click="handleResetPassword(row.id)">重置密码</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="page-container" style="display: flex;justify-content: end;">
      <el-pagination 
        layout="total, prev, pager, next, sizes, jumper"
        :total="total" 
        :page-sizes="[2, 5, 10, 20, 100]"
        v-model:page-size="params.pageSize"
        v-model:current-page="params.page"
        @change="getList()"
      />
    </div>
    <el-dialog v-model="addDialogVisible" title="添加员工" width="600px" @close="onClose">
      <div class="form-container">
        <el-form 
          :model="addForm" 
          :rules="rules"
          ref="addFormRef"
          label-width="100px"
          label-position="top"
        >
          <el-form-item 
            label="员工姓名" 
            prop="name"
    
          >
            <el-input v-model="addForm.name" placeholder="请填写员工姓名" />
          </el-form-item>

          <el-form-item 
            label="登录账号" 
            prop="userName" 
     
          >
            <el-input v-model="addForm.userName" placeholder="请填写登录账号" />
          </el-form-item>

          <el-form-item 
            label="联系方式" 
            prop="phonenumber"
    
          >
            <el-input maxlength="11" v-model="addForm.phonenumber" placeholder="请填写联系方式" />
          </el-form-item>

          <el-form-item label="默认密码">
            <div class="text-gray-500">123456</div>
          </el-form-item>

          <el-form-item 
            label="分配角色" 
            prop="roleId"
    
          >
            <el-select v-model="addForm.roleId" placeholder="请选择分配角色">
              <el-option 
                v-for="role in roleList" 
                :key="role.roleId" 
                :label="role.roleName" 
                :value="role.roleId"
              />
            </el-select>
          </el-form-item>

          <el-form-item 
            label="员工状态" 
            prop="status"
            
          >
            <el-radio-group v-model="addForm.status">
              <el-radio :label="0">禁用</el-radio>
              <el-radio :label="1">启用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button type="primary" :loading="isLoading" @click="onSubmit">提交</el-button>
        <el-button @click="onClose">取消</el-button>
      </template>
      {{ addForm }}
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.building-container {
  padding: 20px;
}

.search-container {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237, 237, 237, .9);
  ;
  padding-bottom: 20px;

  .search-label {
    width: 100px;
  }

  .search-main {
    width: 220px;
    margin-right: 10px;
  }
}

.create-container {
  margin: 10px 0px;
}

.page-container {
  padding: 4px 0px;
  text-align: right;
}

.form-container {
  padding: 0px 80px;
}
</style>